var app = getApp(),
  a = app.requirejs("core"),
  info = app.getCache("userinfo"),
  s = app.requirejs("wxParse/wxParse");
module.exports = {
  //跳转小程序，web网页，内部页面
  to_url:function(k,url,appid='',path='',title=''){
    console.log(k)
      if(k==1){
        if(url)
        {
          if(url.length > 0)
          {
            a.jump(url);  
          }
        }
      } else if (k == 2) {//跳转小程序
        wx.navigateToMiniProgram({
          appId: appid,
          path: path,
          extraData: {
            foo: 'bar'
          },
          envVersion: 'release',
          success(res) {
           console.log('打开成功')
          },
          // fail:function(res){
          //   a.alert('请绑定小程序');
          // }
        })  
      } else if (k == 3) {//web网页
        a.jump('/yb_mingpian/pages/web/index?url=' + escape(url) + '&name=' + title);
       // a.jump(url);
      } else if (k == 4) {//打电话
        if (phone) {
          wx.makePhoneCall({
            phoneNumber: phone
          })
        } else {
          that_.alert('电话不能为空');
        }
      } else if (k == 5) {//地图
        if (lat && lng) {
          that_.tx_map(lat, lng, title);
        } else {
          that_.alert('请完善位置信息');
        }

      } else {
        return;
      }
  },
  /**
   * 缓存省市县地址1
   */
  getArea: function () {
    a.get("area/GetArea", {}, function (e) {
      app.globalData.areas = e.areas
    })
  },
  /**
    * 获取文章列表
    */
  article_list: function (ident, page,class_id,that,obj) {
    var e = {};
      a.get("Article/Article", {
       page:page,
       ident: ident,
       class_id: class_id
      }, function (t) {
        if (t.code == 0) {
          if (t.info.info) {
            t.info.info.length > 0 && (e.page = page + 1, e.list = that.data.list.concat(t.info.info), t.info.info.length < 10 && (e.loaded = true));
            t.info.info.length == 0 && (e.loaded = true);
          e.show = true;
          }else{
            e.loaded = true;
            e.show = true;
          }
          // 使用 decodeURIComponent 的时候报错 Uncaught URIError: URI malformed,因为字符串中可能包含%,需要对其进行转义
          var title = t.info.article_name.replace(/%/g,'%25');
          wx.setNavigationBarTitle({
            title: t.info.article_name ? decodeURIComponent(title) : '文章列表'
          }) 
          e.class_style = t.info.class_style;
        } else {
          a.alert(t.msg,function(){
            return;
          })
        }
        typeof obj == "function" && obj(e)
      },true)
  },

  /**
   * 文章详情
   */
  ArticleInfo: function (ident, id, that, obj) {
    var e = {};
      a.get("Article/ArticleInfo", {
        article_id:id,
        ident: ident
      }, function (t) {
        // 使用 decodeURIComponent 的时候报错 Uncaught URIError: URI malformed,因为字符串中可能包含%,需要对其进行转义
        var title = t.info.title.replace(/%/g,'%25');
        wx.setNavigationBarTitle({
          title: t.info.title ? decodeURIComponent(title) : '详情'
        })

        if (t.code == 0) {
          try {
            s.wxParse("wxParseData", "html", t.info.content, that, "0");
            e.use_wxParse = true;
            console.log("use wxParse !!!");
          }
          catch (err) {
            e.use_wxParse = false;
            console.log("not use wxParse !!!");
          }
          e.detail = t.info;
          e.detail.click = parseInt(e.detail.click) + 1;
          e.show = true;
          typeof obj == "function" && obj(e)
        } else {
          a.alert(t.msg)
        } 
      })
  },
 
  /**
  * 相册
  */
  ImageInfo: function (ident, page, group_id, that, obj) {
    var e = {};
      a.get("Album/Album", {
        page: page,
        ident: ident,
        group_id: group_id
      }, function (t) {
        if (t.code == 0) {
          if (t.info.info){
          t.info.info.length > 0 && (e.page = page + 1, e.list = that.data.list.concat(t.info.info), t.info.info.length < 10 && (e.loaded = true));
          t.info.info.length == 0 && (e.loaded = true);
          e.show = true;
          }else{
            e.loaded = true;
            e.show = true; 
          }
          wx.setNavigationBarTitle({
            title: t.info.group_name ? t.info.group_name: '相册'
          }) 
        } else {
          a.alert(t.msg, function () {
            return;
          })
        }
        typeof obj == "function" && obj(e)
      }, true) 
  },
  /**
   * 官网首页模块化
   */
  indexMod: function (that, obj, func = 'modindex', uid = 0) {
    var _this=this,
      e = {},
      width = wx.getSystemInfoSync().windowWidth;
      //cache = app.getCache("indexMod");

    // if (cache) {
    //   typeof obj == "function" && obj(cache)
    // } else {
      var width = wx.getSystemInfoSync().windowWidth;
      a.get("index/" + func, {uid:uid}, function (i) {
        
        if (typeof i =='string'){
          i = a.json_parse(i);
        }
        console.log("res",i)

        if (func == 'userCenter') {
          var lxm = {info:i,code:0};
          i = lxm;
          console.log('userCenter',i)
        }

        if (i.code == 0) {
          console.log("BarTitle",i.info.name)
          // wx.setNavigationBarTitle({
          //   title: i.info.name ? i.info.name : "商城"
          // })
          if (func != 'userCenter') {
            that.setData({
              page_type: i.info.page_type,
              show_chat: i.info.show_chat
            })
            if (i.info.page_type == 1) {
              _this.to_url(2, '', i.info.appid, i.info.remark, i.info.name);
              return;
            } else if (i.info.page_type == 2) {
              //_this.to_url(3, i.info.remark, '', '', i.info.name);
              that.setData({
                web_url: i.info.remark
              })
              return;
            }
          }
          console.log('userCenter123',i.info.all_data)
          i.info.all_data.forEach(function (k,index){
             //计算广告高度
            if(k.type=="advert"){
              k.high = width * k.ly_height / 10
              //k.high = k.ly_height / 10 * width * 2;
            }
            //计算轮播图高度
            if (k.type == "banner") {
              //k.high = width * k.ly_height / k.ly_width
              k.high = width * k.ly_height / 10
            }
            //地图
            if (k.type == "position") {
              that.setData({
                "markers[0].latitude": k.lat != '' ? k.lat : 34.643330,
                "markers[0].longitude": k.lon != '' ? k.lon : 112.408450,
                  // "markers[0].callout.company": k.name,
                  // "markers[0].callout.content": k.name,
                "markers[0].title": k.name
              })
                k.lat = k.lat != '' ? k.lat : 34.643330,
                k.lon = k.lon != '' ? k.lon : 112.408450,
                _this.companyInfo(that, k.name)
                console.log(k,'kkkkkkk')
            }
            // else if (k.type == "position" && k.is_display==undefined) {
            //
            // }

            //富文本
            if (k.type == "rich_text") {
              s.wxParse("wxParseData_" + k.time_key, "html", k.content, that, "0");
              k.wxParseData = that.data['wxParseData_' + k.time_key].nodes;
            }
            //图片列表数组转json字符串
            if (k.type == "edit_piclist") {
             k.arr=a.str(k.list);
            }
            //悬浮图标
            if (k.type =="floaticon"){
              //  var bili=(25/width)*100;
              //  if (k.b_form_margin<bili){
              //    k.b_form_margin = bili;
              //  } else if (k.b_form_margin > (100 - bili) ){
              //    k.b_form_margin = 100 - bili;
              //  }
            }

            //商品集，1-手动；2-自动
            if (k.type == "goods" && k.add_type==2) {
              //_this.goodslist(that, k.add_num,k.add_sort,k.add_cate, index)
              _this.goodslist(that, k.list, index)
            } else if (k.type == "goods" && k.add_type == undefined) {
              var goods = that.data.goods ? that.data.goods:{};
              goods[index] = k.list;
              that.setData({ goods: goods});
            }

            //文章集
            if (k.type == "article_list" && k.add_type == 2) {
              //_this.articlelist(that, k.add_num, k.add_sort, k.add_cate, index)
              _this.articlelist(that, k.list, index)
            } else if (k.type == "article_list" && k.add_type == undefined) {
              var article = that.data.article ? that.data.article : {};
              article[index] = k.list;
              that.setData({ article: article });
            }

            //产品集
            if (k.type == "product_list" && k.add_type == 2) {
              //_this.productlist(that, k.add_num, k.add_cate, index)
              _this.productlist(that, k.list, index)
            } else if (k.type == "product_list" && k.add_type == undefined) {
              var product = that.data.product ? that.data.product : {};
              product[index] = k.list;
              that.setData({ product: product });
            }

            //评论
            if (k.type == "comment") {

              _this.comment(that, k.is_display)
            }

            //秒杀
            if (k.type == "miaosha") {
              _this.miaosha(that, k.list,index)
            }

            // 砍价
            if (k.type == "kanjia") {
              _this.kanjia(that, k.list, index)
            }

            // 拼团
            if (k.type == "pintuan") {
              _this.pintuan(that, k.list, index)
            }

            //背景音乐
            if (k.type == 'edit_music') {
              // _this.play_music(k.name ? k.name : '车那是', k.author ? k.author : '车那是', k.imgurl, k.url);
              that.setData({ audioSrc: k.url });
              console.log(k.url,'kkkkkkkkkkkk')
            }
            //万能表单
            if (k.type == 'edit_form') {
              if (k.param && k.param != '' && k.param != 0){
                _this.get_form_list(2, k.param, that);
                e.id = k.param;
              }
                
            }
            
          })
          e.index = i.info.all_data;
          e.page = i.info.page;
          //e.page_type=i.info.name;

          if (func == 'modindex') {
            e.index_page_name = i.info.index_name;
          } else if (func == 'ModShop') {
            e.shop_page_name = i.info.shop_name;
          } else {
            e.ucenter_page_name = i.info.ucenter_name;
          }

          e.type=i.info.type;
          e.show = true;
          e.shop_site=i.info.shop_site==1?"2":"top";
          e.is_writeoff = i.info.is_writeoff == undefined ? 0 : i.info.is_writeoff
          //app.setCache("indexMod", e, 1);//1秒
          console.log("index_info",e)
          typeof obj == "function" && obj(e)
        } else {
          a.alert(i.msg ? i.msg:'数据异常')
        }
      },!that.data.show)
    //}
  }, 
  
 // 万能页面
    power: function (id, that, obj) {
        var _this = this,
            e = {},
            width = 375;

        var width = wx.getSystemInfoSync().windowWidth;
        a.get("index/power", {id:id}, function (i) {
            if (i.code == 0) {
                wx.setNavigationBarTitle({
                    title: i.info.name ? i.info.name : '万能页面'
                })
                i.info.all_data.forEach(function (k,index) {
                    //计算广告高度
                    if (k.type == "advert") {
                        k.high = width * k.ly_height / k.ly_width
                    }
                    //计算轮播图高度
                    if (k.type == "banner") {
                        //k.high = width * k.ly_height / k.ly_width
                        k.high = width * k.ly_height / 10
                    }
                    //地图
                    if (k.type == "position" && k.is_display == 2) {
                        that.setData({
                            "markers[0].latitude": k.latitude,
                            "markers[0].longitude": k.longitude,
                            "markers[0].title": k.position_name
                        })
                    }
                    //富文本
                    if (k.type == "rich_text") {
                        s.wxParse("wxParseData_" + k.time_key, "html", k.content, that, "0");
                        k.wxParseData = that.data['wxParseData_' + k.time_key].nodes;
                    }
                    //图片列表数组转json字符串
                    if (k.type == "edit_piclist") {
                        k.arr = a.str(k.list);
                    }
                    //悬浮图标
                    if (k.type == "floaticon") {

                    }

                    //商品集
                    if (k.type == "goods" && k.add_type==2) {
                        //_this.goodslist(that, k.add_num,k.add_sort,k.add_cate, index)
                        _this.goodslist(that, k.list, index)
                    } else if (k.type == "goods" && k.add_type == undefined) {
                        var goods = that.data.goods ? that.data.goods:{};
                        goods[index] = k.list;
                        that.setData({ goods: goods});
                    }

                    //文章集
                    if (k.type == "article_list" && k.add_type == 2) {
                        //_this.articlelist(that, k.add_num, k.add_sort, k.add_cate, index)
                        _this.articlelist(that, k.list, index)
                    } else if (k.type == "article_list" && k.add_type == undefined) {
                        var article = that.data.article ? that.data.article : {};
                        article[index] = k.list;
                        that.setData({ article: article });
                    }

                    //产品集
                    if (k.type == "product_list" && k.add_type == 2) {
                        //_this.productlist(that, k.add_num, k.add_cate, index)
                        _this.productlist(that, k.list, index)
                    } else if (k.type == "product_list" && k.add_type == undefined) {
                        var product = that.data.product ? that.data.product : {};
                        product[index] = k.list;
                        that.setData({ product: product });
                    }

                    //秒杀
                    if (k.type == "miaosha") {

                        _this.miaosha(that, k.list,index)
                    }
                    //评论
                    if (k.type == "comment") {

                        _this.comment(that, k.is_display)
                    }

                    // 砍价
                    if (k.type == "kanjia") {
                        _this.kanjia(that, k.list, index)
                    }

                    // 拼团
                    if (k.type == "pintuan") {
                        _this.pintuan(that, k.list, index)
                    }

                    //背景音乐
                    if (k.type == 'edit_music') {
                        // _this.play_music(k.name ? k.name : 'sb', k.author ? k.author :'sb', k.imgurl, k.url);
                      that.setData({ audioSrc: k.url });
                    }
                    //万能表单
                    if (k.type == 'edit_form') {
                        if (k.param && k.param!='' && k.param!=0){
                            _this.get_form_list(3, k.param, that);
                            e.id = k.param;
                        }
                    }
                })
                e.index = i.info.all_data;
                e.show = true;
                //app.setCache("power", e, 5);//5秒
                typeof obj == "function" && obj(e)
            } else {
                a.alert(i.msg)
            }
        }, true)
        //}
    },

  // 获取公司信息
  companyInfo: function (that,name){
    a.get("User/About", {}, function (res) {
      console.log(res,'test2s')
      if (res.code == 0) {
        that.setData({
          "markers[0].callout.content": res.info.name + '\n' + '地址：' + name,
          "markers[0].callout.company": res.info.name
        })
      } else {
        console.log("companyInfo:fail",res.msg)
      }
    })
  },

  play_music: function (title, singer, coverImgUrl,src){
    if (src && src!=''){
      const backgroundAudioManager = wx.getBackgroundAudioManager()
      backgroundAudioManager.title = title
      backgroundAudioManager.singer = singer
      backgroundAudioManager.coverImgUrl = coverImgUrl
      backgroundAudioManager.src = src // 设置了 src 之后会自动播放
    }
  },

  // 获取商品集
  goodslist:function(that, list, index){
    var goods = [];
    if (list.length > 0) {
      var ids = '';
      list.forEach(function (v) {
        if (v.param != undefined) {
          ids = ids + v.param + ',';
        } else {
          var arrUrl = v.url.split("=");
          if (!isNaN(arrUrl[1])) {
            ids = ids + arrUrl[1] + ',';
          }
        }
      })
      ids = ids.substr(0, ids.length - 1);
      console.log("goods_ids",ids);
      a.get("Index/goodsMod", {ids: ids}, function (res) {
        if (res.code == 0) {
          var goods = that.data.goods ? that.data.goods : {};
          goods[index] = res.info;
          that.setData({goods: goods});
        } else {
          //e.alert(i.msg)
        }
      })
    }
  },

  articlelist: function(that, list, index) {
    var article = [];
    if (list.length > 0) {
      var ids = '';
      list.forEach(function (v) {
        if (v.param != undefined) {
          ids = ids + v.param + ',';
        } else {
          var arrUrl = v.url.split("=");
          if (!isNaN(arrUrl[1])) {
            ids = ids + arrUrl[1] + ',';
          }
        }
      })
      ids = ids.substr(0, ids.length - 1);

      a.get("Index/articleMod", {ids: ids}, function (res) {
        if (res.code == 0) {
          var article = that.data.article ? that.data.article : {};
          article[index] = res.info;
          that.setData({article: article});
        } else {
          //e.alert(i.msg)
        }
      })
    }
  },

  // 获取产品集
  productlist: function(that, list, index) {
    var product = [];
    if (list.length > 0) {
      var ids = '';
      list.forEach(function (v) {
        if (v.param != undefined) {
          ids = ids + v.param + ',';
        } else {
          var arrUrl = v.url.split("=");
          if (!isNaN(arrUrl[1])) {
            ids = ids + arrUrl[1] + ',';
          }
        }
      })
      ids = ids.substr(0, ids.length - 1);
      a.get("Index/productMod", {ids: ids}, function (res) {
        if (res.code == 0) {
          var product = that.data.product ? that.data.product : {};
          product[index] = res.info;
          that.setData({product: product});
        } else {
          //e.alert(i.msg)
        }
      })
    }
  },

  miaosha:function(that,list,index){
    var miaosha = [],
      ids='';
    if(list.length>0){
      list.forEach(function(v,k){
        ids = ids + v.param+',';
      })
      ids = ids.substr(0, ids.length - 1);  
      a.get("Miaosha/msGoodsmodel", { ids: ids}, function (t) {
        if (t.code == 0) {
          if (t.info.length > 0) {
            miaosha = t.info;
            t.info.forEach(function (v2, k2) {
              //倒计时
              if (v2.status > 0) {
                if (v2.status == 2) {
                  var time = v2.etime;
                } else if (v2.status == 1) {
                  var time = v2.stime;
                }
                a.Countdown(time, function (i) {
                  var mscountDownList = that.data.mscountDownList ? that.data.mscountDownList : {};
                  if (!mscountDownList[index]){
                    mscountDownList[index]=[];
                  }     
                  mscountDownList[index][k2]=i;
                  that.setData({ mscountDownList: mscountDownList });
                })
              }
            })
          }
          var miaoshalist = that.data.miaoshalist ? that.data.miaoshalist : {};
          if (!miaoshalist[index]) {
            miaoshalist[index] = [];
          }
          miaoshalist[index] = miaosha;
          that.setData({
            miaoshalist: miaoshalist
          })
        }
      })
    }
  },

  // 获取砍价列表
  kanjia: function (that, list, index) {
    var kanjia = [],
        ids = '';
    if (list.length > 0) {
      list.forEach(function (v, k) {
        ids = ids + v.param + ',';
      })
      ids = ids.substr(0, ids.length - 1);
      a.get("Bargain/kjGoodsmodel", { ids: ids }, function (t) {
        if (t.code == 0) {
          if (t.info.length > 0) {
            var kanjialist = that.data.kanjialist ? that.data.kanjialist : {};
            console.log(kanjialist,'kanjialistkanjialistkanjialist')
            if (!kanjialist[index]) {
              kanjialist[index] = [];
            }
            kanjialist[index] = t.info;
            that.setData({
              kanjialist: kanjialist
            })
          }
        }
      })
    }
  },

  // 获取拼团列表
  pintuan: function (that, list, index) {
    var pintuan = [],
        ids = '';
    if (list.length > 0) {
      list.forEach(function (v, k) {
        ids = ids + v.param + ',';
      })
      ids = ids.substr(0, ids.length - 1);
      a.get("Pintuan/ptGoodsmodel", { ids: ids }, function (t) {
        if (t.code == 0) {
          console.log("pt",t);
          if (t.info.length > 0) {
            var pintuanlist = that.data.pintuanlist ? that.data.pintuanlist : {};
            if (!pintuanlist[index]) {
              pintuanlist[index] = [];
            }
            pintuanlist[index] = t.info;
            //console.log("pintuan"+index,pintuanlist);
            that.setData({
              pintuanlist: pintuanlist
            })
          }
        }
      })
    }
  },

  comment: function (that,num) {
    a.get("Index/CommentList", { num:num }, function (i) {
      if (i.code == 0) {
        var a = { sroce: i.info.sroce, count: i.info.count };
        a.commentlist = i.info.info;
        that.setData(a)
      } else {
        e.alert(i.msg)
      }
    })
  },
  /**
    * 获取文章分类
    */
  Article_Class: function (ident_class, that) {
    var e = {};
    wx.getSystemInfo({
      success: function (res) {
        var height = (res.windowWidth - 20) * 0.50 * 0.90;
        that.setData({ height: height })
      }
    })
    a.get("Article/ArticleClass", {
      ident_class: ident_class
    }, function (t) {
      if (t.code == 0) {
        if (t.info) {
          e.list=t.info;
          e.show = true;
          that.setData(e);
        }
      } else {
        a.alert(t.msg)
      }
      //typeof obj == "function" && obj(e)
    }, true)
  },
  /**
    * 获取相册分类
    */
  Album_Class: function (ident_class, that) {
    var e = {};
    wx.getSystemInfo({
      success: function (res) {
        var height = (res.windowWidth - 20) * 0.50 * 0.90;
        that.setData({ height: height })
      }
    })
    a.get("Album/AlbumImages", {
      ident_class: ident_class
    }, function (t) {
      if (t.code == 0) {
        if (t.info) {
          e.list = t.info
          e.show = true;
          that.setData(e);
        }
      } else {
        a.alert(t.msg)
      }
      //typeof obj == "function" && obj(e)
    }, true)
  },

  //表单提交
  formSubmit: function (that, e) {
    var that_ = this,
    form = that.data.form,
      data = e.detail.value;
    that_.validate(data, form, function (k) {//字段验证
      if (k == 0) {
        data = JSON.stringify(that_.to_str(data, form));//转换字段格式

        a.loading('正在提交中...');
        a.post('index/submitform', {
          data: data,
          form: JSON.stringify(form),
          bus_form_id: that.data.form_id,
          user_id: app.getCache("userinfo").uid
        }, function (t) {
          a.hideLoading();
          if (t.code == 0) {
            a.success('提交成功');
            setTimeout(function () {
              that.get_list();
            }, 1e3);
          } else {
            a.alert(t.msg);
          }
        })
      } else {
        return;
      }
    });

  },

  bindPickerChange: function (that, e) {
    var id = e.target.id,
      data = that.data.data;
    data[id] = e.detail.value;
    that.setData({
      data: data
    })
  },

  listen_time_two: function (that, e) {
    var id = e.target.id,
      key = e.currentTarget.dataset.key,
      data = that.data.data;
    data[id + '_' + key] = e.detail.value;
    if (key == 2) {
      if (a.time_str(data[id + '_1']) >= a.time_str(data[id + '_2'])) {
        a.error('不小于开始时间');
        return;
      }
      data[id] = data[id + '_1'] + ',' + data[id + '_2'];
    }
    that.setData({
      data: data
    })
  },
  Image_del: function (that,e) {
    var index = a.pdata(e).index,
      key = a.pdata(e).key,
      arr = that.data.data;
    a.removeByValue(arr[key], index, function (i) {
      arr[key] = i;
      that.setData({
        data: arr
      })
    })
  },

  //获取表单
  get_form_list: function (type_,id, that) {

    var form = app.siteInfo.form, data = {};
    var button_name = '提交';
    a.get('index/form', {
      id: id
    }, function (t) {
      var form = t.info.list;
      if (t.code == 0) {
        if (type_==1){
          // 使用 decodeURIComponent 的时候报错 Uncaught URIError: URI malformed,因为字符串中可能包含%,需要对其进行转义
          var title = t.info.title.replace(/%/g,'%25');
          wx.setNavigationBarTitle({
            title: t.info.title ? decodeURIComponent(title) : '万能表单'
          })
          if (form.length == 0) {
            a.alert('表单内容为空');
            return;
          }
        }
        form.forEach(function (k) {
          if (k.module == 'picker') {
            data[k.name] = 0;
          };
          if (k.module == 'time_one') {
            data[k.name] = k.default;
          };
          if (k.module == 'time_two') {
            data[k.name + '_1'] = k.default1;
            data[k.name + '_2'] = k.default2;
            if (k.default1 && k.default2) {
              data[k.name] = k.default1 + ',' + k.default2;
            } else {
              data[k.name] = '';
            }
          };
          if (k.module == 'pic_arr') {
            data[k.name] = [];
          };
          if (k.module == 'region') {
            data[k.name] = k.default;
            data[k.name + '_multi'] = [0, 0, 0];
          }

          if (k.module == 'button') {
            button_name = k.title;
          };
        })
        if (type_ == 1){
          that.setData({
            show:true
          })
        }

        that.setData({
          data: data,
          button_name: button_name,
          form: form,
          form_id:id
        })
      } else {
        a.alert(t.msg);
      }
    }, true)

  },

  //过滤字段，转换字段格式
  to_str: function (data, list) {
    var that = this, arr = [];
    for (let i in data) {
      arr.push({ 'name': i, 'value': data[i] });
    }
    if (arr.length > 0) {
      arr.forEach(function (k) {
        for (var i = 0; i < list.length; i++) {
          if (k.name == list[i].name) {
            if (list[i].module == 'checkbox') {
              data[k.name] = data[k.name].join(',');
            }
            // if (list[i].module == 'region') {//input自动转数组为字符串了
            //  // data[k.name] = data[k.name].join(',');
            // }
          }
        }
      })
      return data;
    } else {
      a.error('表单不能为空');
      return;
    }
  },

  //字段验证
  validate: function (data, list, obj) {
    var arr = [], n = 0, that = this;
    for (let i in data) {
      arr.push({ 'name': i, 'value': data[i] });
    }
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        var res = that.in_array(arr[i].name, arr[i].value, list);
        if (res['code'] == 1) {
          n++;
          a.error(res.msg);
          break;
        }
      }
      "function" == typeof obj && obj(n)
    } else {
      a.error('表单不能为空');
      return;
    }
  },

  //错误判断
  in_array: function (name, value, list) {
    var data = { 'code': 0 };
    list.forEach(function (k) {
      if (k.name == name) {
      
        //判断不能为空
        if (k.empty) {
          if (!value || value.length == 0) {//判断字段是否空值
            data['code'] = 1;
            data['msg'] = k.title + '不能为空';
            return data;//字段不能能为空
          }

        }
        // if (k.module == 'time_two') {

        // }
      }
    })
    return data;
  },

  /**
  * 图片上传
  * this
  * n文件夹名称
  * key 0多图上传，1单图上传
  */
  upload: function (that, field, n, key = 0) {
    var _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that, field, n, key)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, field, n, key)
          }
        }
      }
    })
  },
  chooseWxImage: function (type_, that, field, n, key) {
    var _this = this,
      site = getApp().siteInfo,
      arr = that.data.data ? that.data.data : {},
      url = site.siteroot + '?i=' + site.uniacid + '&t=undefined&v=' + site.version + '&from=wxapp&c=entry&a=wxapp&do=index_uploadFile&path=' + n + '&m=yb_mingpian&sign=5201314';
      
    arr[field] = arr[field] ? arr[field] : [];

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type_],
      success: function (res) {
        
        if (key == 0) {
          res.tempFilePaths.forEach(function (t) {
            wx.uploadFile({
              url: url,
              filePath: t,
              name: 'file_upload',
              success: function (res) {
                console.log(res.data)
                if (res.data != null && res.data != '') {

                  arr[field] = arr[field].concat(res.data);
                  that.setData({
                      data: arr
                    })
                  //var data = a.json_parse(res.data);
                  
                  // if (data.code == 0) {
                  //   arr[field] = arr[field].concat(data.info);
                  //   that.setData({
                  //     data: arr
                  //   })
                  // } else {
                  //   a.error(data.msg)
                  // }
                } else {
                    a.error(data.msg)
                  }
              }
            })
          })
        } else {
          wx.uploadFile({
            url: url,
            filePath: res.tempFilePaths[0],
            name: 'file_upload',
            success: function (res) {
           
              if (res.data != null && res.data != '') {
                console.log(res.data)
                arr[field] = res.data;
                that.setData({
                    data: arr
                  })
                // var data = a.json_parse(res.data);
                // if (data.code == 0) {
                //   //var arr = that.data.data;
                //   arr[field] = data.info;
                //   that.setData({
                //     data: arr
                //   })
                // } else {
                //   a.error(data.msg)
                // }
              } else {
                  a.error('上传失败，请重试')
                }
            }
          })
        }
      }
    })
  },
//版本号比较
  versionfunegt:function (ver1, ver2) {
    var version1next = ver1.replace(".", "");
    var version2next = ver2.replace(".", "");
    var version1pre = parseFloat(version1next);
    var version2pre = parseFloat(version2next);
    if (version1pre < version2pre) {
      return false;
    } else {
        return true;
    }
    
  }
}
